var express = require('express');
var formidable = require('formidable');
var fs = require('fs');
var LogItemManager = require("../manager/LogItemManager");
var logger = new require("../log/Logger")("UploadRouter");

var UploadRouter = express.Router();

UploadRouter.use(function(req, res, next) {
    next();
});

UploadRouter.post('/upload', function(req, res) {
    var form = new formidable.IncomingForm(); //创建上传表单
    form.encoding = 'utf-8'; //设置编辑
    form.uploadDir = 'upload-temp/'; //设置上传目录
    form.keepExtensions = true; //保留后缀
    form.maxFieldsSize = 2 * 1024 * 1024; //文件大小
    logger.info("file income!");
    form.parse(req, function(err, fields, files) {
        var logFilePath = files.logFile.path;
        LogItemManager.processNewLog(fields.appId, fields.appKey, files.logFile.path).then(function(){
            fs.unlink(logFilePath);
            res.end(JSON.stringify({
                code: 0,
                message: ""
            }));
        }, function(){
            fs.unlink(logFilePath);
            res.end(JSON.stringify({
                code: -1,
                message: "没有这个APP Key"
            }));
        }).catch(function(err){
            logger.error(err);
            res.end(JSON.stringify({
                code: -100,
                message: "服务器异常"
            }));
        });
    });
});

module.exports = UploadRouter;
